# 静态首页
from collections import OrderedDict
from django.template import loader
from django.conf import settings

import os
from contents.utils import get_categories
from contents.models import ContentCategory


def generate_static_index_html():
    """
    生成静态的主页html文件
    """
    print('%s: generate_static_index_html')

    # 查询并展示商品频道和分类
    categories = get_categories()
    # 查询首页广告数据
    contents = {}
    content_categories = ContentCategory.objects.all()
    for cat in content_categories:
        contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')
    # 构造上下文, 渲染模板
    context = {
        'categories':categories,
        'contents':contents
    }
    # 获取首页模板文件
    template = loader.get_template('index.html')
    # 渲染首页html字符串
    # html_text = template.render(context)
    # 将首页html字符串写入到指定目录，命名'index.html'

    # 渲染模板的第二种写法, 得到渲染后的字符串
    html_text = loader.render_to_string('index.html', context)

    # 将渲染后的模板字符串存储在指定路径下的 index.html 文件中
    file_path = os.path.join(settings.STATICFILES_DIRS[0], 'index.html')
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(html_text)

